package kr.or.kead.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import kr.or.kead.domain.Employee;
import kr.or.kead.util.Mysql_con;

public class DaoEmp implements DaoTable {

	@Override
	public int insertDao(Object obj) {
		Connection con = Mysql_con.getConnection();
		Employee emp = (Employee)obj;
		String sql = "INSERT INTO emp (e_code, e_name, e_grade) values (?, ?, ?)";
		PreparedStatement pstm = null;
		
		try {
			pstm = con.prepareStatement(sql);
			System.out.println(emp.getE_code());
			System.out.println(emp.getE_name());
			System.out.println(emp.getE_level());
			pstm.setString(1, emp.getE_code());
			pstm.setString(2, emp.getE_name());
			pstm.setString(3, emp.getE_level());
			
			pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		} finally {			
			try {
				pstm.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return 0;
	}

	@Override
	public int deleteDao(String code) {
		Connection con = Mysql_con.getConnection();
		String sql = "DELETE FROM emp WHERE e_code = ?";
		PreparedStatement pstm = null;		
		try {
			pstm = con.prepareStatement(sql);
			pstm.setString(1, code);			
			pstm.executeUpdate();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return -1;
		} finally {			
			try {
				pstm.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return 0;
	}

	@Override
	public Object selectDao(String code) {
		Connection con = Mysql_con.getConnection();
		String sql = "SELECT e_code, e_name, e_grade FROM emp" +
						" WHERE e_code = ?";
		PreparedStatement pstm = null;
		ResultSet rs = null;
		Employee emp = null;
		
		try {
			pstm = con.prepareStatement(sql);
			pstm.setString(1, code);
			rs = pstm.executeQuery();
			if(rs.next()) {
				emp = new Employee();
				emp.setE_code(rs.getString("e_code"));
				emp.setE_name(rs.getString("e_name"));
				emp.setE_level(rs.getString("e_grade"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} finally {			
			try {
				pstm.close();
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		return emp;
	}

}
